<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleCurrentChange(1)">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table
      v-loading="listLoading"
      :data="items"
      highlight-current-row
      style="width: 100%"
      @selection-change="selsChange"
      @sort-change="sortChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="60" />
      <el-table-column prop="voteId" label="投票编号" sortable="custom" />
      <el-table-column prop="voteName" label="投票名" sortable="custom" />
      <el-table-column prop="bgnDate" label="开始时间" sortable="custom" />
      <el-table-column prop="endDate" label="结束时间" sortable="custom" />
      <el-table-column prop="description" label="简介" sortable="custom" />
      <el-table-column prop="status" label="是否显示" sortable="custom">
        <template slot-scope="scope">
          <el-tag effect="dark" :type="Tool.statusFilter(scope.row.status)">{{ menusStatus[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否结束" sortable="custom">
        <template slot-scope="scope">
          <el-tag effect="dark" :type="Tool.statusFilter(scope.row.isFinished)">{{
            menusStatus[scope.row.isFinished]
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="270">
        <template slot-scope="scope">
          <p class="table-button">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit-outline"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleDel(scope.$index, scope.row)"
            >删除</el-button>
          </p>
          <p class="table-button">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-film"
              @click="handleOption(scope.$index, scope.row)"
            >选项</el-button>
            <el-button
              type="success"
              size="small"
              icon="el-icon-pie-chart"
              @click="handleChart(scope.$index, scope.row)"
            >图表</el-button>
          </p>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="sels.length === 0" @click="batchRemove">批量删除</el-button>
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :current-page.sync="page"
        :page-size="10"
        :total="total"
        style="float: right"
        @current-change="handleCurrentChange"
      />
    </el-col>

    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="dbFormVisible" :close-on-click-modal="false">
      <el-form ref="dbForm" :model="dbForm" label-width="100px" :rules="dbFormRules">
        <el-form-item label="投票名称" prop="voteName">
          <el-input v-model="dbForm.voteName" auto-complete="off" />
        </el-form-item>
        <el-form-item label="开始时间" prop="bgnDate">
          <el-date-picker v-model="dbForm.bgnDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker v-model="dbForm.endDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="dbForm.description" :rows="5" type="textarea" auto-complete="off" />
        </el-form-item>
        <el-form-item label="是否显示" prop="status">
          <el-radio-group v-model="dbForm.status">
            <el-radio class="radio" :label="0">隐藏</el-radio>
            <el-radio class="radio" :label="1">显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否结束" prop="isFinished">
          <el-radio-group v-model="dbForm.isFinished">
            <el-radio class="radio" :label="0">进行中</el-radio>
            <el-radio class="radio" :label="-1">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dbFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="dbLoading" @click.native="dbSubmit">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选项" :visible.sync="optionFormVisible" :close-on-click-modal="false">
      <el-tabs v-model="activeOptionName" @tab-click="handleOptionTabsClick">
        <el-tab-pane label="新增/编辑选项" name="form">
          <el-form ref="optionForm" :model="optionForm" label-width="100px" :rules="optionFormRules">
            <el-form-item label="选项标题" prop="optionName">
              <el-input v-model="optionForm.optionName" auto-complete="off" />
            </el-form-item>
            <el-form-item label="选项简介" prop="description">
              <el-input v-model="optionForm.description" :rows="5" type="textarea" auto-complete="off" />
            </el-form-item>
            <el-form-item label="是否显示" prop="status">
              <el-radio-group v-model="optionForm.status">
                <el-radio class="radio" :label="0">隐藏</el-radio>
                <el-radio class="radio" :label="1">显示</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="操作">
              <el-button type="primary" :loading="dbLoading" @click.native="dbSubmitOption">提交</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="选项列表" name="list">
          <div>
            <el-row>
              <el-col
                v-for="voteOption in voteOptions"
                :key="voteOption.optionId"
                :span="8"
              ><div>
                <p>
                  <el-row :gutter="20" class="option-info">
                    <el-col :span="8"><el-tag type="info">选项名称</el-tag> </el-col>
                    <el-col :span="16">{{ voteOption.optionName }}</el-col>
                  </el-row>
                  <el-row :gutter="20" class="option-info">
                    <el-col :span="8"><el-tag type="success">选项描述</el-tag> </el-col>
                    <el-col :span="16">{{ voteOption.description }}</el-col>
                  </el-row>
                  <el-row :gutter="20" class="option-info">
                    <el-col :span="8"><el-tag type="success">是否显示</el-tag> </el-col>
                    <el-col
                      :span="16"
                    ><el-tag effect="dark" :type="Tool.statusFilter(voteOption.status)">{{
                      menusStatus[voteOption.status]
                    }}</el-tag></el-col>
                  </el-row>
                </p>
                <p>
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit-outline"
                    @click.native="dbEditOption(voteOption)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click.native="dbDeleteOption(voteOption)"
                  >删除</el-button>
                </p>
              </div></el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="optionFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="图表" :visible.sync="chartFormVisible" :close-on-click-modal="false" @opened="getChartData">
      <div ref="chart" style="width: 600px; height: 400px" />
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="chartFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import Api from '@/api/api'
import Tool from '@/utils/tool'
import echarts from 'echarts'

export default {
  data() {
    return {
      Tool,
      pageController: 'vote',
      filters: {
        address: '',
        name: ''
      },
      menus: {
      },
      items: [],
      total: 0,
      page: 1,
      order: '',
      sortby: '',
      listLoading: false,
      sels: [], // 列表选中列

      dbFormVisible: false, // 编辑界面是否显示
      dbMethod: '', // 是更新还是新增操作
      dbLoading: false,
      dbFormRules: {
        voteName: [{ required: true, message: '请输入投票名称', trigger: 'blur' }]
      },
      // 编辑界面数据
      dbForm: {
        voteId: 0,
        voteName: '',
        status: 0,
        description: '',
        bgnDate: '',
        endDate: '',
        isFinished: 0
      },
      menusStatus: {
        0: '否',
        1: '是'
      },
      // 选项
      optionFormVisible: false,
      optionMethod: 'create',
      activeOptionName: 'list',
      voteOptions: [],
      optionForm: {
        optionId: 0,
        optionName: '',
        description: '',
        status: 1
      },
      optionFormRules: {
        optionName: [{ required: true, message: '请输入选项标题', trigger: 'blur' }],
        description: [{ required: true, message: '请输入选项简介', trigger: 'blur' }]
      },
      // 图表
      chartFormVisible: false,
      chartForm: {
        voteId: 0,
        opinion: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎'],
        opinionData: [
          { value: 335, name: '直接访问' },
          { value: 310, name: '邮件营销' },
          { value: 234, name: '联盟广告' },
          { value: 135, name: '视频广告' },
          { value: 1548, name: '搜索引擎' }
        ]
      }

    }
  },
  mounted() {
    this.getList()
    this.getMenus()
  },
  methods: {
    handleCurrentChange(val) {
      this.page = val
      this.getList()
    },
    // 获取用户列表
    getList() {
      const vue = this
      Tool.getList(vue, { voteName: vue.filters.name })
    },
    getMenus() {
      const vue = this
      Tool.getMenus(vue)
    },
    handleChart: function(index, row) {
      this.chartFormVisible = true
      this.chartForm.voteId = row.voteId
    },
    getChartData() {
      Api.http
        .get(Api.ajaxUrl + '/votes/' + this.chartForm.voteId + '/pie')
        .then(data => {
          if (data.code === 0) {
            this.chartForm.opinion = data.opinion
            this.chartForm.opinionData = data.opinionData
            this.drawPie()
          }
        })
        .catch(() => {})
    },
    drawPie() {
      this.charts = echarts.init(this.$refs.chart)
      this.charts.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b}:{c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          x: 'left',
          data: this.chartForm.opinion
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'blod'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: this.chartForm.opinionData
          }
        ]
      })
    },
    handleOptionTabsClick(tab, event) {
      if (tab.name === 'form') {
        this.resetOptionForm()
      }
    },
    getVoteOptions(voteId) {
      Api.http
        .get(Api.ajaxUrl + '/votes/' + voteId + '/options')
        .then(data => {
          if (data.code === 0) {
            this.voteOptions = data.options
          }
        })
        .catch(() => {})
    },
    handleOption: function(index, row) {
      this.getVoteOptions(row.voteId)
      this.optionFormVisible = true
      this.optionForm.voteId = row.voteId
    },
    dbEditOption: function(voteOption) {
      this.optionForm = Object.assign({}, voteOption)
      this.optionMethod = 'update'
      this.activeOptionName = 'form'
    },
    dbDeleteOption: function(voteOption) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const params = {
          id: voteOption.optionId
        }
        Api.service
          .remove('option', params)
          .then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getVoteOptions(voteOption.voteId)
          })
          .catch(() => {})
      })
    },
    dbSubmitOption: function() {
      const vue = this
      vue.$refs.optionForm.validate(valid => {
        if (valid) {
          vue.$confirm('确认提交吗？', '提示', {}).then(() => {
            vue.dbLoading = true
            const params = Object.assign({}, vue.optionForm)
            if (vue.optionMethod === 'create') {
              Api.service
                .add('option', params)
                .then(res => {
                  vue.dbSuccessOption(params.voteId)
                })
                .catch(() => {
                  vue.dbLoading = false
                })
            } else {
              Api.service
                .edit('option', params)
                .then(res => {
                  vue.dbSuccessOption(params.voteId)
                })
                .catch(() => {
                  vue.dbLoading = false
                })
            }
          })
        }
      })
    },
    dbSuccessOption(voteId) {
      this.dbLoading = false
      this.$message({
        message: '提交成功',
        type: 'success'
      })
      this.resetOptionForm()
      this.activeOptionName = 'list'
      this.getVoteOptions(voteId)
    },
    resetOptionForm() {
      this.$refs['optionForm'].resetFields()
      this.optionMethod = 'create'
      // 注意voteId不能清空
      this.optionForm = {
        voteId: this.optionForm.voteId,
        optionName: '',
        description: '',
        status: 1
      }
    },
    // 删除
    handleDel: function(index, row) {
      const vue = this
      Tool.handleDel(vue, { id: row[this.pageController + 'Id'] })
    },
    // 显示编辑界面
    handleEdit: function(index, row) {
      this.dbFormVisible = true
      this.dbMethod = 'update'
      this.dbForm = Object.assign({}, row)
    },
    // 显示新增界面
    handleAdd: function() {
      this.dbFormVisible = true
      this.dbMethod = 'create'
      this.dbForm = {
        voteId: 0,
        voteName: '',
        status: 0,
        description: '',
        bgnDate: '',
        endDate: '',
        isFinished: 0
      }
    },
    // 编辑
    dbSubmit: function() {
      const vue = this
      Tool.dbSubmit(vue)
    },
    dbSuccess() {
      const vue = this
      Tool.dbSuccess(vue)
    },
    selsChange: function(sels) {
      this.sels = sels
    },
    sortChange(column) {
      const vue = this
      Tool.sortChange(vue, column)
    },
    // 批量删除
    batchRemove: function() {
      const vue = this
      const ids = vue.sels.map(item => item[this.pageController + 'Id']).toString()
      Tool.batchRemove(vue, ids)
    }
  }
}
</script>

<style scoped>
.table-button {
  margin: 2px 0px;
}
span.label {
  margin: 5px;
}
.option-info {
  margin-bottom: 20px;
}
.option-info:last-child {
  margin-bottom: 0;
}
</style>
